﻿using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Linq;
using Xinchen.SOA.Server;
using Xinchen.SOA.Server.ControllerResolver;
using Xinchen.SOA.Server.Formatters;
using Xinchen.SOA.Server.Handlers;
using Xinchen.SOA.Server.ServiceHosting;
using System.Net.Http.Formatting;
using System.Net.Http;
using Newtonsoft.Json;
[assembly: OwinStartup(typeof(Startup))]
namespace Xinchen.SOA.Server
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            //var xsoaSection = (ConfigSection)ConfigurationManager.GetSection("xsoa");
            //if (xsoaSection == null)
            //{
            //    throw new Exception("未找到xsoa配置节");
            //}
            //if (xsoaSection.Contracts != null)
            //{
            //    var types = new List<Type>();
            //    try
            //    {
            //        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            //        foreach (var ass in assemblies)
            //        {
            //            if (ass.IsDynamic)
            //            {
            //                continue;
            //            }
            //            types.AddRange(ass.GetExportedTypes().Where(x => typeof(ServiceObject).IsAssignableFrom(x)));
            //        }
            //    }
            //    catch (FileNotFoundException)
            //    {

            //    }
            //    catch (TypeLoadException)
            //    {

            //    }
            //    int applicationId = 0;
            //    if (!int.TryParse(xsoaSection.ApplicationId, out applicationId) || applicationId <= 0)
            //    {
            //        throw new Exception("applicationId错误");
            //    }
            //    HttpClient client = new HttpClient();
            //    UpdateServicesRequest request = new UpdateServicesRequest();
            //    using (client)
            //    {
            //        request.ApplicationId = applicationId;
            //        request.ApplicationKey = xsoaSection.ApplicationKey;
            //        request.ServiceInfos = new List<UpdateServiceInfo>();
            //        foreach (Contract item in xsoaSection.Contracts)
            //        {
            //            var contractType = Type.GetType(item.Type);
            //            if (contractType == null)
            //            {
            //                throw new Exception(contractType + "在程序集中没有找到");
            //            }
            //            if (!contractType.IsInterface)
            //            {
            //                throw new Exception(contractType + "不是接口");
            //            }
            //            var contractClassTypes = types.Where(x => contractType.IsAssignableFrom(x));
            //            if (contractClassTypes.Count() > 1)
            //            {
            //                throw new Exception("契约的实现类只能有一个");
            //            }
            //            var contractClassType = contractClassTypes.FirstOrDefault();
            //            var serviceInfo = new UpdateServiceInfo();
            //            serviceInfo.ContractName = contractType.FullName;
            //            serviceInfo.ServiceClassName = contractClassType.FullName;
            //            serviceInfo.ServiceName = item.Name;
            //            serviceInfo.Actions.AddRange(contractType.GetMethods().Select(x => x.Name));
            //            var responseMessage = client.PostAsJsonAsync(AppConfig.SOAUpdateServiceUrl, serviceInfo).Result;
            //            var response = responseMessage.Content.ReadAsStringAsync().Result;
            //            var updateResponse = JsonConvert.DeserializeObject<UpdateServicesResponse>(response);
            //            if (updateResponse.ResultCode != 0)
            //            {
            //                throw new Exception(updateResponse.ResultMessage);
            //            }
            //        }
            //    }
            //}


            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}"
            );
            config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
            config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
            config.MessageHandlers.Add(new CountDownHandler());
            config.Services.Replace(typeof(IActionValueBinder), new ActionValueBinder());
            config.Services.Replace(typeof(IHttpActionInvoker), new ControllerActionInvoker());
            config.Services.Replace(typeof(IHttpControllerSelector), new ControllerSelector(config));
            config.Services.Replace(typeof(IHttpActionSelector), new HttpActionSelector());
            config.Services.Replace(typeof(IHttpControllerActivator), new HttpControllerActivitor());
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DateTimeConverter());
            appBuilder.UseWebApi(config);
        }
    }
}
